<!--出租房 修改 -->
<template>
  <div
    class="app-container"
    v-loading.fullscreen="loading"
    :element-loading-text="loadText"
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.8)"
  >
    <div class="d-flex ai-center header-process fs-l" :style="{ left: sidebar.opened ? '210px' : '54px' }">
      <div>房源信息完整程度</div>
      <el-progress class="flex-1" :stroke-width="14" :percentage="percentage" style="margin-left: 5px"></el-progress>
      <div>(完整程度100%才能使用一键发房)</div>
    </div>
    <div class="nav-box">
      <el-collapse-transition>
        <div v-show="navShow">
          <div
            v-for="(item, i) in navList"
            :key="item.title"
            :class="{ 'nav-item': true, select: navCurrentIndex == i }"
            @click="handleAnchor(i, item.nav)"
          >
            {{ item.title }}
          </div>
        </div>
      </el-collapse-transition>
      <div @click="navShow = !navShow" :class="['nav-item', navShow ? '' : 'select']">
        <span :class="[navShow ? 'el-icon-arrow-up' : 'el-icon-arrow-down', 'fs-xxl']"></span>
      </div>
    </div>
    <div>
      <com-title-item title="房源信息修改" v-if="true" :class="{ 'whole-rent': houDelVO.rentType == '整租' }">
        <el-form :model="houDelVO" label-width="110px" size="mini" style="margin-top: 20px">
          <el-form-item
            v-for="configItem in configHouse"
            ref="formItemList"
            :label="configItem.title"
            :key="configItem.title"
            :prop="configItem.key"
            :rules="configItem.rules || []"
          >
            <!-- 单选 -->
            <template v-if="configItem.isRadio && configItem.options">
              <el-radio-group v-model="houDelVO[configItem.key]">
                <el-radio
                  :class="{ multiple: configItem.options.length > 10 }"
                  v-for="(item, i) in configItem.options"
                  :label="item"
                  :key="i"
                  >{{ configItem.format ? configItem.format(item) : item }}</el-radio
                >
              </el-radio-group>
            </template>

            <!-- 多选 -->
            <template v-else-if="configItem.isCheckbox && configItem.options">
              <el-checkbox
                :indeterminate="checkboxConfig[configItem.key].isIndeterminate"
                v-model="checkboxConfig[configItem.key].checkAll"
                @change="handleChangeAll(configItem.key, $event)"
                >全选</el-checkbox
              >
              <el-checkbox-group
                v-model="houDelVO[configItem.key]"
                @change="handleCheckboxChange(configItem.key, $event)"
              >
                <el-checkbox v-for="item in configItem.options" :label="item" :key="item">{{
                  configItem.format ? configItem.format(item) : item
                }}</el-checkbox>
              </el-checkbox-group>
            </template>

            <!-- 单输入框 -->
            <template v-else-if="configItem.isInput">
              <el-input
                :disabled="configItem.disabled"
                :suffix-icon="configItem.disabled ? 'el-icon-lock' : ''"
                v-model="houDelVO[configItem.key]"
                :class="{
                  'reject-input': !isValidValue(houDelVO[configItem.key]) && configItem.required,
                }"
                :style="{ width: '178px' }"
              >
                <i v-if="configItem.unit" slot="suffix" style="font-style: normal">{{ configItem.unit }}</i>
              </el-input>
            </template>

            <!-- 多输入框 -->
            <template v-else-if="configItem.isMultiple">
              <el-row :gutter="10">
                <template v-for="(item, i) in configItem.contents">
                  <el-col :span="configItem.contents.length==5? 2 : 3" :key="i">
                    <el-form-item :prop="item.key" :rules="item.rules || []">
                      <el-input
                        v-model="houDelVO[item.key]"
                        :placeholder="item.placeholder"
                        :readonly="item.readonly"
                        :class="{
                          'reject-input':
                            configItem.required &&
                            (configItem.checkValue
                              ? !configItem.checkValue(houDelVO[item.key])
                              : !isValidValue(houDelVO[item.key])),
                        }"
                      >
                        <i slot="suffix" style="font-style: normal">{{ item.unit }}</i>
                      </el-input>
                    </el-form-item>
                  </el-col>
                </template>
              </el-row>
            </template>

            <!-- 日期选择 -->
            <template v-else-if="configItem.isDate">
              <el-date-picker
                v-model="houDelVO.earlyTime"
                type="date"
                value-format="timestamp"
                placeholder="随时"
                :picker-options="pickerOptions"
              ></el-date-picker>
            </template>

            <!-- 单项input选择 -->
            <template v-else-if="configItem.isSingleSelect">
              <el-select v-model="houDelVO[configItem.key]" placeholder="请选择">
                <el-option
                  v-for="item in configItem.options"
                  :key="item"
                  :label="configItem.format ? configItem.format(item) : item"
                  :value="item"
                >
                </el-option>
              </el-select>
            </template>

            <!-- 小提示 -->
            <template v-if="configItem.tips">
              <span class="text-gray" style="margin-left: 15px">{{ configItem.tips }}</span>
            </template>
          </el-form-item>
        </el-form>
      </com-title-item>

      <com-title-item title="端口配置" v-if="true" style="position: relative">
        <el-form :model="houDelVO" label-width="110px" size="mini" class="text-gray" style="margin-top: 20px">
          <el-form-item label="平台房源编号" prop="portHouNum" :rules="portHouNumConfig.rules1">
            <el-input v-model="houDelVO.portHouNum" :maxlength="36" style="width: 200px"></el-input>
            <span style="margin-left: 15px">注：此编号推送时对应到各个网站的“房源信息编号”位置。</span>
          </el-form-item>

          <el-form-item label="平台配置" :rules="[{ required: true }]">
            <!-- <div style="margin-left: 15px">
              原户室号：3栋1单元1102（修改原户室号，请到树懒极速版小程序上进行修改）；必须填写完整的对应平台信息，进行判断是否可一键发房操作。
            </div> -->
            <div class="table-body bold fs-md">
              <!-- header-title -->
              <div class="header-title d-flex">
                <div class="flex-1 cell">平台名称</div>
                <div class="flex-1 cell">小区名称</div>
                <div class="flex-3 cell">户室号</div>
                <div class="flex-1 cell">月租金</div>
                <div class="flex-1 cell">面积</div>
                <div class="flex-1 cell">操作</div>
              </div>

              <!-- 组件 -->
              <template v-for="(item, i) in houPortInfo">
                <com-rent-match-item
                  v-if="item.portType === PORT_CODE_AJK"
                  :delId="houDelId"
                  :model="item"
                  :noPortAccount="noPortAccount"
                  :resblockName="houDelVO.resblockName"
                  :key="i"
                  :ref="item.portType"
                  :buildSize="houDelVO.buildSize"
                  :totalPrices="houDelVO.totalPrices"
                  @updateportvo="handleUpdatePortVO"
                  @ontotalpricespassed="(v) => (houDelVO.totalPricesPassed = v)"
                  @ontotalpricesignore="(v) => (houDelVO.totalPricesIgnore = v)"
                ></com-rent-match-item>
              </template>
            </div>
          </el-form-item>
        </el-form>

        <div v-if="noPortAccount == 0" class="lock-box text-white text-center d-flex">
          <div style="margin: auto">
            <div>端口配置需要绑定账号后，才可激活页面哦~</div>
            <el-button type="primary" size="mini" style="margin-top: 20px" @click="handleGoBind">去绑定账号</el-button>
          </div>
        </div>

        <div v-if="noPortAccount == 2" class="lock-box text-white text-center d-flex">
          <div style="margin: auto">
            <div>系统检测到您在58安居客的帐号需要短信验证，验证完即可使用</div>
            <el-button type="primary" size="mini" style="margin-top: 20px" @click="handleGoBind">立即验证</el-button>
          </div>
        </div>

        <div v-if="noPortAccount == 3" class="lock-box text-white text-center d-flex">
          <div style="margin: auto">
            <div>系统检测到您在58安居客的账号密码发生了修改，请修改最新的密码重新绑定后进行使用</div>
            <el-button type="primary" size="mini" style="margin-top: 20px" @click="handleGoBind"
              >重新绑定账号</el-button
            >
          </div>
        </div>
      </com-title-item>

      <com-title-item title="房源介绍" v-if="true">
        <el-form :model="houDelVO" label-width="110px" size="medium" style="margin-top: 20px">
          <el-form-item
            v-for="(item, i) in houseRecommend"
            :label="item.title"
            :key="i"
            :rules="[{ required: item.required }]"
          >
            <el-button size="mini" type="primary" style="margin-bottom: 10px" @click="handleShowPopVisible(item.title)"
              >参考模板</el-button
            >
            <el-input
              type="textarea"
              :placeholder="'请输入' + item.title"
              v-model="houDelRecommendVO[item.key]"
              show-word-limit
              :minlength="item.minlength"
              :maxlength="item.maxlength"
              :rows="item.rows"
              :class="{ 'reject-input': !!houDelRecommendErrorMsg[item.key] }"
              @blur="handleRecommendBlur(item.key, $event, item)"
            ></el-input>
            <div class="d-flex ai-center">
              <div :class="['fs-sm', 'flex-1', houDelRecommendErrorMsg[item.key] ? 'text-red' : 'text-gray']">
                {{ houDelRecommendErrorMsg[item.key] || item.tipsFormat() }}
              </div>
              <el-button size="mini" type="primary" @click="handleSaveModel(item.key)">存储模板</el-button>
            </div>
          </el-form-item>
        </el-form>
      </com-title-item>

      <com-title-item title="图片信息" v-if="true">
        <com-image-list
          :imageVO.sync="imageVO"
          :houDelId="houDelId"
          :isVrHouse="hmDelSummaryInfo.houSubType == 1"
          :houDelVO="houDelVO"
          :houImageVO="houImageVO"
        ></com-image-list>
      </com-title-item>

      <!-- 视频信息 -->
      <com-title-item title="视频信息">
        <com-upload-video
          :hmDelSummaryInfo="hmDelSummaryInfo"
          @onvideoupdate="handleVideoDuringUpdate"
          :room="houDelVO.room"
          :houDelId="houDelId"
        >
          <template #default="{...row}">
            <com-table-video v-bind="row"></com-table-video>
          </template>
        </com-upload-video>
        <div>
          <div class="vr d-flex ai-center fs-l" v-if="showDownLoadVr">
            <div class="title">下载VR房源</div>
            <div class="select">
              <el-radio v-model="radio" label="1">是</el-radio>
              <el-radio v-model="radio" label="2">否</el-radio>
            </div>
          </div>
          <div v-if="showDownLoadVr" class="fs-md text-gray-light" style="margin-top: 10px">
            备注：当房源为VR房源时才可以进行VR下载，VR预计5分钟后下载完成
          </div>
          <div class="comfirm d-flex ai-center jc-center">
            <el-button type="info" @click="$router.back()">取消</el-button>
            <el-button type="primary" :disabled="!saveAble" @click="handleConfirm">保存</el-button>
          </div>
        </div>
      </com-title-item>

      <!-- 配置网络房源介绍的模板 -->
      <com-set-house-model
        :title="houseModelTitle"
        :houDelVO="houDelVO"
        :modelPopVisible.sync="setHouseModelPopVisible"
        @onsetmodel="handleSetModel"
      ></com-set-house-model>

      <!-- 保存成功的弹层 -->
      <el-dialog :visible.sync="nextPopVisible" top="30vh">
        <span slot="title" class="d-flex ai-center">
          <span class="el-icon-success text-green fs-xxxl"></span>
          <span style="margin-left: 8px">保存成功</span>
        </span>
        <span>{{
          houseInfoCompleted
            ? '房源信息已完备，请确认图片水印已去除、房源信息无误后再进行推送～'
            : '房源信息未完善，完善之后才能进行推房～'
        }}</span>
        <span slot="footer" class="dialog-footer">
          <el-button plain @click="nextPopVisible = false">{{
            houseInfoCompleted ? '返回确认' : '立即完善'
          }}</el-button>
          <el-button type="primary" @click="$router.replace({ name: 'rentHouse' })">返回列表</el-button>
          <el-button type="success" @click="handleImmediatePush">立即推送</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import comTitleItem from './com/com-title-item';
import comSetTag from './dialog/com-set-tag';
import ComRentMatchItem from './com/com-rent-match-item';
import comUploadVideo from './com/com-upload-video';
import ComTableVideo from '@/views/house/com/com-table-video';
import comImageList from './com/com-image-list';
import comSetHouseModel from './dialog/com-set-house-model';

import {
  getHouseInfo,
  updateImage,
  updateRecommendInfo,
  getMemberPower,
  submitVrTask,
  saveHouPortInfo,
  houseIllegal,
  updateRentDelInfoWeb,
  savePersonalDefaultInfo,
  examineDelPushAble,
} from '@/api/user';
import { checkPortAccountHandler, menuHandler, checkPortBindByCode } from '@/handler/menuHandler';
import { HOUSE_PUSH, VIP_MESSAGE, VR_COMPOUND_ADD } from '@/config/menuId';
import { PORT_CODE_AJK } from '@/config/house/platform';
import { mapGetters } from 'vuex';
import {
  hallRoomNumber,
  houseImages,
  houseRecommend,
  portHouNumConfig,
  videoTimeList,
} from '@/config/house/houseDetailConfig';
import platform from '@/config/house/platform';
import { baseRentConf, forceHouseInfoHanlder, joinRentConf, wholeRentConf } from '@/config/house/rentConfig';

/** 全部配置数据 */
let configHouse = [...baseRentConf, ...joinRentConf, ...wholeRentConf];

/** 多选框的特殊处理 */
let checkboxConfig = configHouse
  .filter((v) => v.isCheckbox)
  .reduce((res, item) => {
    res[item.key] = {
      title: item.title,
      checkAll: false,
      checkedList: [],
      options: item.options,
      isIndeterminate: false,
    };
    return res;
  }, {});

const navList = [
  { title: '房源信息修改', nav: 0 },
  { title: '端口配置', nav: 1170 },
  { title: '房源介绍', nav: 1400 },
  { title: '图片信息', nav: 2800 },
  { title: '视频信息', nav: 3200 },
];

export default {
  name: 'ModifyHouse',
  components: {
    comTitleItem,
    comSetTag,
    ComRentMatchItem,
    comUploadVideo,
    comImageList,
    comSetHouseModel,
    ComTableVideo,
  },
  props: {
    houDelId: {
      type: String,
      default: '',
    },
  },
  provide() {
    return {
      submitImage: this.submitImage,
      houDelVO: this.houDelVO,
    };
  },
  data() {
    return {
      videoDuringTime: 0, //视频播放时长
      loadText: '拼命加载中...',
      houseModelTitle: '', //设置模板题目
      setDefaultPopVisible: false, //设置默认值的小弹层
      setHouseModelPopVisible: false, //设置房源介绍模板
      houseInfoCompleted: false, //房源信息是否完善
      navShow: true,
      navCurrentIndex: 0,
      navList: navList,
      radio: '1',
      noPortAccount: 0, //没有端口账号
      loading: false,
      nextPopVisible: false, //保存完成后的下一步选择弹层

      checkboxConfig, // 多选的字段配置
      // 基本信息
      houDelVO: {
        id: '',
        delId: '',
        delegationType: '', //委托类型
        resblockName: '', //小区
        area: '', //区域
        addr: '', //地址
        rentType: '', //出租方式
        buildType: '', //房屋类型
        direction: '', //朝向
        decorateType: '', //装修
        elevator: '', //是否配有电梯
        room: '', //室
        hall: '', //厅
        toilet: '', //卫
        cookRoom: '', //厨房
        balcony: '', //阳台
        floor: '', //所在楼层
        totalFloor: '', //总楼层
        buildSize: '', //建筑面积
        totalPrices: '', //租金
        payWay: '', //付款方式
        earlyTime: '', //最早入住时间
        approTime: '', //看房时间

        matchingFacilitiesList: [], //配套设施
        roomEquip: [], //房间设施
        publicEquip: [], //公共设施
        roomShine: [], //房屋亮点
        costDetail: [], //费用明细
        rentRequire: [], //出租要求

        overRentNum: '', //已出租户数
        heRentNum: '', //共出租户数
        waitRentType: '', //待租卧室类型 主卧0/次卧1/其他2
        waitRentOrientation: '', //待租卧室朝向
        waitRentSize: '', //待租面积

        title: '',
        portHouNum: '', //房源编号

        totalPricesPassed: false, //是否总价通过校验
        totalPricesIgnore: false, //是否总价忽略校验

        floorPlan: '1', //占位符字段
      },
      houPortInfo: [], //匹配端口小区信息列表
      houDelRecommendVO: {
        title: '',
        sellingPoint: '', //核心卖点
      },
      // 错误提示
      houDelRecommendErrorMsg: {
        title: '',
        sellingPoint: '', //核心卖点
      },
      imageVO: {
        houseTypeList: [], //房型图
        indoorList: [], //室内图
        circumList: [], //小区图
      },
      houImageVO: [], //图片原始数据
      configHouse,
      hallRoomNumber,
      houseImages: Object.freeze(houseImages),
      portHouNumConfig: Object.freeze(portHouNumConfig),
      houseRecommend: Object.freeze(
        houseRecommend.filter((item) => {
          return item.key == 'title' || item.key == 'sellingPoint';
        }),
      ),
      hmDelSummaryInfo: {}, //关于vr视频的数据
      recommendHushihao: [], //推荐的户室号数据
      pickerOptions: {
        //日期选择限制
        disabledDate: (time) => {
          return time.getTime() <= Date.now() - 8.64e7;
        },
      },
    };
  },
  filters: {},

  created() {
    // window.onscroll = () => {
    //   console.log(document.documentElement.scrollTop)
    // }
    // console.log();
  },
  async mounted() {
    checkPortAccountHandler()
      .then(() => {
        this.noPortAccount = 1;
      })
      .catch((res) => {
        this.noPortAccount = res;
      })
      .finally(() => {
        this.initHouseInfo(this.houDelId);
      });
  },

  computed: {
    ...mapGetters(['sessionUser']),
    ...mapGetters(['sidebar']),
    saveAble({ houDelVO }) {
      return forceHouseInfoHanlder(houDelVO);
    },
    checkPortInfoList() {
      return this.houPortInfo.some((info) => {
        return this.checkPortInfo(info);
      });
    },
    // 计算百分比
    percentage() {
      let total = 0;
      let fill = 0;
      // 基本信息
      this.configHouse.forEach((item) => {
        if (!item.required) return;

        if (item.isMultiple && item.contents) {
          item.contents.forEach((innerItem) => {
            total++;
            let _c = item.checkValue || this.isValidValue;
            if (_c(this.houDelVO[innerItem.key])) {
              fill++;
            }
          });
        } else if (item.key) {
          total++;
          if (this.isValidValue(this.houDelVO[item.key])) {
            if (item.checkValue) {
              if (item.checkValue(this.houDelVO[item.key])) {
                fill++;
              }
            } else {
              fill++;
            }
          }
        }
      });

      // 房源介绍
      this.houseRecommend.forEach((item) => {
        let value = this.houDelRecommendVO[item.key];
        if (!item.required) return;

        let errorMsg = item.rule(value);
        this.houDelRecommendErrorMsg[item.key] = errorMsg;
        total++;
        if (!errorMsg) {
          fill++;
        }
      });

      // 校验图片
      for (let i = 0; i < houseImages.length; i++) {
        total++;
        const item = houseImages[i];
        const imgGroup = this.imageVO[item.key];
        let l = imgGroup.length;
        const lengthFit = l >= item.minlength && l <= item.maxlength;
        const tagFit = imgGroup.every((v) => !v.invalid);
        if (lengthFit && tagFit) {
          fill++;
        }
      }
      // 平台配置相关
      total++;
      if (this.checkPortInfoList) fill++;

      total++;
      if (portHouNumConfig.checkValue1(this.houDelVO.portHouNum)) fill++;
      if (this.getVideoMinTime()) fill--;

      let result = Math.floor((fill / total) * 100);
      return Math.max(result, 0);
    },

    showDownLoadVr() {
      let info = this.hmDelSummaryInfo;
      return info.houSubType == 1 && info.houSubTypeState != 10 && info.houSubTypeState != 1;
    },
  },
  watch: {
    ['houDelVO.rentType'](newValue) {
      if (newValue == '整租') {
        this.configHouse = [...baseRentConf, ...wholeRentConf];
      } else {
        let i = baseRentConf.findIndex((v) => v.key == 'rentType');
        let conf1 = joinRentConf.filter((v) => !v.isCheckbox);
        let conf2 = joinRentConf.filter((v) => v.isCheckbox);

        this.configHouse = [...baseRentConf.slice(0, i + 1), ...conf1, ...baseRentConf.slice(i + 1), ...conf2];
      }
    },
  },

  methods: {
    handleSaveModel(key) {
      let item = this.houseRecommend.find((v) => v.key == key);
      let value = this.houDelRecommendVO[key];

      let errorMsg = item.rule(value);
      if (errorMsg) return this.$message.error(errorMsg);

      savePersonalDefaultInfo({
        tag: item.title,
        material: value,
        delegationType: this.houDelVO.delegationType,
      }).then(({ isSuccess, errorMessage = '添加失败！' }) => {
        if (isSuccess) {
          this.$message.success('添加成功！');
        } else {
          this.$message.error(errorMessage);
        }
      });
    },
    // 打开模板
    handleShowPopVisible(v) {
      this.houseModelTitle = v;
      this.setHouseModelPopVisible = true;
    },
    handleSetModel(v) {
      let item = this.houseRecommend.find((v) => v.title == this.houseModelTitle);
      this.houDelRecommendVO[item.key] = v;
    },
    // 多选框选择全部
    handleChangeAll(key, val) {
      this.houDelVO[key] = val ? this.checkboxConfig[key].options : [];
      this.checkboxConfig[key].isIndeterminate = false;
    },
    handleCheckboxChange(key, value) {
      let checkedCount = value.length;
      let totalCount = this.checkboxConfig[key].options.length;
      this.checkboxConfig[key].checkAll = checkedCount === totalCount;
      this.checkboxConfig[key].isIndeterminate = checkedCount > 0 && checkedCount < totalCount;
    },
    handleVideoDuringUpdate(value) {
      this.videoDuringTime = value;
    },
    // 初始化房源基本信息
    async initHouseInfo(houDelId) {
      this.loading = true;
      const { content, isSuccess, errorCode } = await getHouseInfo({ houDelId });
      if (!isSuccess && errorCode && errorCode === '21007') {
        this.$alert('该房源被删除，无法查看~', '提示', {
          confirmButtonText: '确定',
          showClose: false,
          callback: (action) => {
            this.$router.back();
          },
        });
        return;
      }

      this.hmDelSummaryInfo = content.hmDelSummaryInfo || {};
      content.hmRentDetailVO.portHouNum = content.hmRentDetailVO.portHouNum || '1' + String(Math.random()).slice(-9);

      this.renderHouDel(content.hmRentDetailVO);
      this.houImageVO = Object.freeze(content.houImageVO);
      this.renderRecommend(content.houDelRecommendVO, content.houDelVO.title);
      this.renderPort(content.houPortInfo, content.hmRentDetailVO);

      this.loading = false;
    },

    // 保存
    async handleConfirm() {
      this.loading = true;

      try {
        await this.submitRecommend();
        await this.submitHouDel();
        await this.submitPort();
        await this.submitImage();

        await examineDelPushAble({ delId: this.houDelId });
      } catch (error) {
        this.loading = false;
        return;
      }

      this.loading = false;

      if (!this.showDownLoadVr || this.radio == '2') {
        this.nextPopVisible = true;
        this.houseInfoCompleted = this.percentage == 100;
      } else {
        await this.downLoadVR();
        this.nextPopVisible = true;
        this.houseInfoCompleted = this.percentage == 100;
      }
    },

    // 提交保存房源介绍信息
    submitRecommend() {
      const getErrorMessage = (obj) => {
        return Object.keys(obj).reduce((result, key) => {
          let config = this.houseRecommend.find((v) => v.key == key);
          result += `<p>您的${config.title}包含敏感词汇：${obj[key].join('、')}</p>`;
          return result;
        }, '');
      };

      const nextFn = (obj) => {
        let errorMessage = getErrorMessage(obj);
        return this.$messageBox
          .confirm(`${errorMessage}`, '敏感词提醒：', {
            confirmButtonText: '过滤保存',
            cancelButtonText: '去修改',
            dangerouslyUseHTMLString: true,
          })
          .then(() => {
            for (let key in obj) {
              let reg = new RegExp(obj[key].join('|'), 'g');
              this.houDelRecommendVO[key] = this.houDelRecommendVO[key].replace(/ /g, '').replace(reg, '');
            }

            return this.requeryUpdateRecommendInfo();
          })
          .catch((error) => {
            return Promise.reject();
          });
      };

      return this.sensitiveVerify()
        .then(() => {
          return this.requeryUpdateRecommendInfo();
        })
        .catch((obj) => {
          if (obj === 0) return Promise.reject();
          return nextFn(obj);
        });
    },

    // 敏感词校验接口
    sensitiveVerify() {
      if (this.noPortAccount != 1) return Promise.resolve();
      let keys = Object.keys(this.houDelRecommendVO).filter((v) => v != 'title');
      let checkContent = keys.map((key) => ({ key, value: this.houDelRecommendVO[key] })).filter((v) => !!v.value);
      let param = { title: this.houDelRecommendVO.title, checkContent };

      return houseIllegal(param).then(({ isSuccess, errorMessage, content }) => {
        if (!isSuccess) {
          // console.log("敏感词校验失败 错误信息。。", errorMessage);
          return Promise.resolve();
        }
        if (!content) {
          return Promise.resolve();
        }
        let obj = content.checkContent.reduce(
          (pre, next) => {
            if (next.badWord && next.badWord.length) {
              pre[next.key] = next.badWord;
            }
            return pre;
          },
          content.titleBadWordSet && content.titleBadWordSet.length ? { title: content.titleBadWordSet } : {},
        );

        if (Object.values(obj).length == 0) {
          // console.log("敏感词", obj);
          return Promise.resolve();
        } else {
          return Promise.reject(obj);
        }
      });
    },

    requeryUpdateRecommendInfo() {
      return updateRecommendInfo({
        houDelRecStr: JSON.stringify({
          deleted: false,
          houDelId: this.houDelId,
          ...this.getRecommendVo(),
        }),
      }).then(({ isSuccess, errorMessage = '保存房源介绍信息失败！' }) => {
        if (!isSuccess) {
          this.$message.error(errorMessage);
          return Promise.reject(0);
        }
      });
    },

    getRecommendVo() {
      let vo = Object.keys(this.houDelRecommendVO).reduce((pre, next) => {
        let item = this.houseRecommend.find((v) => v.key == next);
        pre[next] = {
          tag: item.title,
          context: this.houDelRecommendVO[next],
        };
        return pre;
      }, {});
      return vo;
    },

    // 保存端口匹配信息
    submitPort() {
      if (this.noPortAccount != 1) return Promise.resolve();

      const result = this.houPortInfo.map((item) => {
        return {
          delId: this.houDelId,

          portResblockName: item.portResblockName,
          portBuild: item.portBuild,
          portUnit: item.portUnit,
          portDoorNum: item.portDoorNum,

          platformResblockId: item.platformResblockId,
          platformBuildId: item.platformBuildId,
          platformUnitId: item.platformUnitId,
          platformDoorNumId: item.platformDoorNumId,

          huShiHao: item.huShiHao,
          buildSizeLocked: item.buildSizeLocked,
          totalPricesPassed: item.totalPricesPassed,
          totalPricesIgnore: item.totalPricesIgnore,

          totalPrice: this.setTotalPrices(this.houDelVO, item.totalPrice),
          buildingSize: item.buildingSize,
          publishSize: item.publishSize,

          portTags: this.getPortTagValue('text', this.portTags).join(','),
          portType: item.portType,
          delPercentage: String(this.percentage / 100),
          onePushFlag: this.checkPortInfo(item) ? '0' : '1',
          delegationType: 'RENT',
        };
      });

      return saveHouPortInfo(result).then(({ isSuccess, errorMessage = '' }) => {
        if (!isSuccess) {
          return this.$messageBox
            .confirm(`保存端口配置失败，${errorMessage}`, {
              confirmButtonText: '我知道了',
              showCancelButton: false,
            })
            .finally(() => {
              return Promise.reject();
            });
        }
      });
    },

    // 校验户室号是否ok (租房中只要匹配到小区即可)
    checkPortInfo(info) {
      return !!info.portResblockName;
    },

    // 更新端口信息
    handleUpdatePortVO(info) {
      const i = this.houPortInfo.findIndex((v) => v.portType == info.portType);
      this.$set(this.houPortInfo, i, info);

      // console.log("同步过来== ", info.platformResblockId);
    },

    // 渲染端口号
    renderPort(houPortInfo, houDelVO) {
      if (this.noPortAccount != 1) return;

      const list = Object.keys(platform).map((key) => {
        let info = houPortInfo.find((v) => v.portType == key) || { portType: key };

        // 新添字段
        info.totalPrice = this.getTotalPrices(houDelVO, info.totalPrice || houDelVO.totalPrices);
        info.buildingSize = info.buildingSize || houDelVO.buildSize;

        return info;
      });

      // 暂时本地只有一个portTags
      let tags = (list[0].portTags || '').split(',').filter((v) => !!v);
      this.portTags = this.getPortTagValue('value', tags);
      this.houPortInfo = list;
    },

    // 渲染房源介绍推荐信息
    renderRecommend(list = {}, title) {
      list.title = { tag: '房源标题', context: title };
      for (let key in this.houDelRecommendVO) {
        if (list && list[key]) {
          let item = this.houseRecommend.find((v) => v.key == key);
          let text = list[key].context || item.defaultValue || '';
          text = text.replace(/ /g, '');
          text = text.slice(0, item.maxlength);
          this.houDelRecommendVO[key] = text;
        }
      }
    },
    // 锚点
    handleAnchor(i, nav) {
      if (typeof nav == 'undefined') {
        nav = navList[i].nav;
      }
      if (nav || nav === 0) {
        this.navCurrentIndex = i;
        document.documentElement.scrollTop = document.body.scrollTop = nav;
      } else {
        this.navCurrentIndex = 0;
        if (this.navList.length == 1) {
          this.navList = navList;
        } else {
          this.navList = [navList[navList.length - 1]];
        }
      }
    },
    downLoadVR() {
      return menuHandler
        .call(this, VR_COMPOUND_ADD)
        .then(() => {
          submitVrTask({
            delId: this.houDelId,
          }).then(() => {
            this.hmDelSummaryInfo.houSubTypeState = 1;
          });

          // 下载vr
          getMemberPower({
            menuId: VR_COMPOUND_ADD,
            agentId: this.sessionUser.id,
          });

          return this.$messageBox
            .confirm('vr房源下载中，需要3-5分钟', {
              confirmButtonText: '我知道了',
              showCancelButton: false,
            })
            .finally(() => {
              return Promise.resolve();
            });
        })
        .catch((error) => {
          if (error && error.then) {
            return error.then(() => Promise.reject());
          } else {
            return Promise.resolve();
          }
        });
    },

    handleGoBind() {
      this.submitHouDel();
      this.submitImage();

      this.$router.push({ name: 'portManagement' });
    },

    isVipMember() {
      return new Promise((resolve, reject) => {
        menuHandler
          .call(this, HOUSE_PUSH)
          .then(() => {
            resolve();
          })
          .catch((error) => {
            reject();
          });
      });
    },

    // 发房
    async handleImmediatePush() {
      if (!(await checkPortBindByCode(PORT_CODE_AJK))) return this.$message.error('您暂未绑定可推送的安居客端口账号，请先绑定后再进行推送~');

      try {
        await this.isVipMember();
      } catch (error) {
        return;
      }

      if (this.checkValues()) {
        return;
      }
      if (!this.checkPortInfoList) {
        return this.$message.error('端口配置小区尚未匹配！');
      }
      if (!portHouNumConfig.checkValue1(this.houDelVO.portHouNum)) {
        return this.$message.error('平台房源编号有误！');
      }

      // 校验图片
      for (let i = 0; i < houseImages.length; i++) {
        const item = houseImages[i];
        const vo = this.imageVO[item.key];
        let l = vo.length;
        if (l < item.minlength) {
          this.$message.error(`${item.title}不足${item.minlength}张`);
          return;
        } else if (l > item.maxlength) {
          this.$message.error(`${item.title}超过${item.maxlength}张`);
          return;
        }

        for (let j = 0; j < vo.length; j++) {
          const element = vo[j];
          if (element.invalid) {
            this.$message.error(`${item.title}尺寸不合格`);
            return;
          }
        }
      }

      this.nextPopVisible = false;
      this.$router.push({
        name: 'sendHouse',
        query: { delId: [this.houDelId], delegationType: 'RENT' },
      });
    },

    // 校验基本信息 返回true表示校验有误
    checkValues() {
      for (let i = 0; i < this.configHouse.length; i++) {
        const item = this.configHouse[i];
        if (!item.required) continue;

        if (item.isMultiple && item.contents && item.checkValue) {
          for (let j = 0; j < item.contents.length; j++) {
            const element = item.contents[j];
            if (!item.checkValue(this.houDelVO[element.key])) {
              this.$message.error(`${item.title}未填或不合格`);
              return true;
            }
          }
        } else if (item.key) {
          if (item.checkValue && !item.checkValue(this.houDelVO[item.key])) {
            this.$message.error(`${item.title}未填或不合格`);
            return true;
          }

          if (item.isRadio) {
            if (!this.houDelVO[item.key] && this.houDelVO[item.key] !== 0) {
              this.$message.error(`${item.title}未选`);
              return true;
            }
          }
        }
      }

      for (let i = 0; i < this.houseRecommend.length; i++) {
        const item = this.houseRecommend[i];
        if (!item.required) continue;

        let value = this.houDelRecommendVO[item.key] || '';
        let errorMsg = item.rule(value);
        if (errorMsg) {
          this.$message.error(errorMsg);
          return true;
        }
      }

      return false;
    },

    handleRecommendBlur(key, e, item) {
      this.houDelRecommendVO[key] = (this.houDelRecommendVO[key] || '').replace(/ /g, '');
    },

    /** 房源基本信息渲染 */
    renderHouDel(vo) {
      vo.cookRoom = vo.cookRoom === 0 ? 1 : vo.cookRoom;
      vo.balcony = vo.balcony === 0 ? 1 : vo.balcony;

      for (let key in vo) {
        if (Number(vo[key]) === -1) vo[key] = '';
      }
      vo.totalPrices = this.getTotalPrices(vo);

      configHouse
        .filter((item) => {
          return item.isRadio && item.options;
        })
        .forEach((item) => {
          if (!item.options.includes(vo[item.key])) {
            vo[item.key] = item.default || '';
          }
        });

      for (let key in this.houDelVO) {
        if (key in vo) {
          this.houDelVO[key] = vo[key];
        }
      }
    },

    /** 获取视频最小时长限制 */
    getVideoMinTime() {
      let room = this.houDelVO.room;
      if (room && room != '0' && this.videoDuringTime) {
        let minTime = videoTimeList[room] || Math.max.apply(null, Object.values(videoTimeList));
        if (this.videoDuringTime < minTime) {
          return `${room}室户上传视频不得小于${minTime}秒`;
        }
      }
      return '';
    },

    // 提交保存基本信息
    submitHouDel() {
      let errorMsg = this.getVideoMinTime();
      if (errorMsg) {
        return this.$messageBox
          .confirm(errorMsg, {
            confirmButtonText: '我知道了',
            cancelButtonText: '去修改',
          })
          .finally(() => {
            return Promise.reject();
          });
      }

      let obj = {
        ...this.houDelVO,
        delId: this.houDelId,
        earlyTime: this.houDelVO.earlyTime || null,
        title: this.houDelRecommendVO.title,
        totalPrices: this.setTotalPrices(this.houDelVO),
        delPercentage: String(this.percentage / 100),
      };
      console.log('出租保存：== ', obj);
      return updateRentDelInfoWeb({
        houDelStr: JSON.stringify(obj),
      }).then(({ isSuccess, errorMessage = '' }) => {
        if (!isSuccess) {
          if (this.houDelVO.hasOwnProperty(errorMessage)) {
            this.houDelVO[errorMessage] = '';
          }

          return this.$messageBox
            .confirm(`保存房源基本信息失败，${errorMessage}`, {
              confirmButtonText: '我知道了',
              showCancelButton: false,
            })
            .finally(() => {
              return Promise.reject();
            });
        }
      });
    },

    submitImage() {
      let houImgList = [...this.imageVO.indoorList, ...this.imageVO.houseTypeList, ...this.imageVO.circumList];
      houImgList.forEach((item, index) => {
        item.cover = index;
      });

      if (houImgList.length == 0) {
        return Promise.resolve();
      }

      return updateImage({ houImgList })
        .catch((error) => {
          this.$message.error('图片保存超时！');
          return Promise.reject();
        })
        .then(({ isSuccess, errorMessage = '' }) => {
          if (!isSuccess) {
            return this.$messageBox
              .confirm(`保存图片失败，${errorMessage}`, {
                confirmButtonText: '我知道了',
                showCancelButton: false,
              })
              .finally(() => {
                return Promise.reject();
              });
          }
        });
    },
  },
};
</script>

<style scoped>
ul {
  padding: 0;
  margin: 0;
}
.modify-box {
  position: relative;
  overflow: hidden;
}
.header-process {
  position: fixed;
  left: 0;
  right: 0;
  top: 84px;
  background: #fff;
  z-index: 10;
  padding: 0 50px 0 30px;
  line-height: 30px;
  transition: all 0.3s;
  box-shadow: 0 5px 10px rgba(0, 0, 0, 0.1);
}
.nav-box {
  position: fixed;
  width: 120px;
  text-align: center;
  line-height: 50px;
  background: rgba(255, 255, 255, 0.7);
  box-shadow: rgba(0, 0, 0, 0.3) 0px 0px 15px;
  z-index: 10;
  cursor: pointer;
  right: 0;
  top: 30%;
}
.nav-box .nav-item {
  display: block;
  border-bottom: 1px solid #eee;
}
.nav-box .nav-item.select {
  background: rgb(68, 161, 255);
  color: #fff;
}
.lock-box {
  background: rgba(0, 0, 0, 0.5);
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  border-radius: 5px;
}

.app-container {
  background: #f6f6f6;
  padding-top: 50px;
}

.app-container .comfirm {
  margin-top: 30px;
}

.app-container .table-body {
  margin-top: 10px;
  border-bottom: 1px solid #dfe6ec;
  border-right: 1px solid #dfe6ec;
}

.app-container .table-body .header-title {
  background: #edf6ff;
}
.cell {
  border-left: 1px solid #dfe6ec;
  border-top: 1px solid #dfe6ec;
  padding: 5px 10px;
}

.vr {
  margin-top: 50px;
}
.vr .title {
  margin-right: 10px;
}

.vr .select {
  margin-right: 30px;
}

.reject-input >>> .el-textarea__inner {
  border-color: red;
}
.reject-input >>> .el-input__inner {
  border-color: red;
}
.recommend-hsh {
  padding-bottom: 20px;
  max-height: 300px;
  overflow-y: auto;
}
.recommend-hsh-item {
  width: 170px;
  padding: 10px 0;
  border: 1px solid rgb(37, 146, 251);
  border-radius: 5px;
  margin-right: 20px;
  margin-bottom: 15px;
}
.recommend-hsh-item.more {
  color: white;
  background-color: rgb(37, 146, 251);
}

.fade-line-enter-active,
.fade-line-leave-active {
  transition: all 0.5s;
}
.fade-line-enter,
.fade-line-leave-to {
  opacity: 0;
  transform: translateX(36px);
}
.app-container >>> .el-form--inline .el-form-item--mini {
  margin-bottom: 0px;
}
.app-container >>> .el-row .el-form-item--mini {
  margin-bottom: 0px;
}
</style>
